class HttpUtil {
  constructor() {
    this.cookies = {};
  }
  request(options) {
    const cookieHeader = this._buildCookieHeader();

    const newOptions = {
      ...options,
      header: {
        ...options.header,
        Cookie: cookieHeader,
      },
    };
    return new Promise((resolve, reject) => {
      const _this = this;
      wx.request({
        ...newOptions,
        success(res) {
          if (res.statusCode === 200) {
            _this._extractAndStoreCookies(res.header);
            resolve(res);
          } else {
            reject(new Error(`请求失败，状态码: ${res.statusCode}，请重试或联系管理员。`));
          }
        },
        fail(err) {
          reject(err);
        },
      });
    });
  }

  _extractAndStoreCookies(header) {
    if (!header) return;

    // 处理Set-Cookie头（可能存在多个）
    const setCookieHeaders = header['Set-Cookie'] || header['set-cookie'];

    if (!setCookieHeaders) return;

    // 将Set-Cookie头转换为数组处理
    const cookiesArray = Array.isArray(setCookieHeaders) ? setCookieHeaders : [setCookieHeaders];

    // 解析每个cookie并存储
    cookiesArray.forEach((cookieStr) => {
      // 提取cookie名称和值（格式：name=value; ...）
      const cookieParts = cookieStr.split(';')[0].split('=');
      if (cookieParts.length >= 2) {
        const name = cookieParts[0].trim();
        const value = cookieParts[1].trim();
        this.cookies[name] = value;
      }
    });
  }

  // 构建Cookie请求头字符串
  _buildCookieHeader() {
    return Object.entries(this.cookies)
      .map(([name, value]) => `${name}=${value}`)
      .join('; ');
  }
}

const instance = new HttpUtil();
module.exports = instance;
